#include <stdio.h>
#include <stdlib.h>

#include "point_list.h"

PointList * newPointList(int initCapacity){
	int i;
	PointList * pl = (PointList *)malloc(sizeof(PointList));
	pl->length = 0;
	pl->capacity = initCapacity;

	pl->points = (Point **)malloc(initCapacity * sizeof(Point *));
	for(i = 0; i < initCapacity; i++)
		pl->points[i] = newPoint();
	return pl;
}

void freePointList(PointList * pl){
	int i;
	for(i = 0; i < pl->capacity; i++){
		if(pl->points[i] != NULL)
			free(pl->points[i]);
	}
	free(pl->points);
	free(pl);
}

void addPoint(PointList * pl, Point * p){
	if(pl->length < pl->capacity){
		pl->points[pl->length]->x = p->x;
		pl->points[pl->length++]->y = p->y;
	}
}

void deletePoint(PointList * pl, int idx){
	int i;
	if(idx >= 0 && idx < pl->length){
		for(i = idx; i < pl->length-1; i++)
			pl->points[i] = pl->points[i+1];
		pl->points[pl->length-1] = NULL;
		pl->length--;
	}
}

void sortPointList(PointList * pl){
	pointListQuickSort(pl, 0, pl->length-1);
}

void pointListQuickSort(PointList * pl, long left, long right){
	long m;
	long i;
	if(left < right){
		m = left;
		for(i = left+1; i <= right; i++)
			if(compare(pl->points[i], pl->points[left]) > 0){
				//printf("compare=%d\n", compare(pl->points[i], pl->points[left]));
				swap(pl->points[++m], pl->points[i]);
			}
				
		swap(pl->points[left], pl->points[m]);
		pointListQuickSort(pl, left, m-1);
		pointListQuickSort(pl, m+1, right);
	}
}

void swap(Point * p1, Point * p2){
	Point * tmp = newPoint();
	tmp->x = p1->x;
	tmp->y = p1->y;
	p1->x = p2->x;
	p1->y = p2->y;
	p2->x = tmp->x;
	p2->y = tmp->y;
	free(tmp);
}

void printPointList(PointList * pl){
	int i;
	printf("PointList-------------------\n");
	for(i = 0; i < pl->length; i++)
		printPoint(pl->points[i]);
	printf("----------------------------\n");
}

void printUsedPoints(PointList * pl){
	int i;
	for(i = 0; i < pl->length; i++)
		if(pl->points[i]->used)
			printf("%g %g\n", pl->points[i]->x, pl->points[i]->y);
}

int containsPoint(PointList * pl, Point * p){
	int i;
	for(i = 0; i < pl->length; i++){
		if(compare(p, pl->points[i]) == 0)
			return 1;
	}
	return 0;
}